package com.bajie.bjlisten.sevice;


import com.bajie.bjlisten.entity.BjRole;
import com.bajie.bjlisten.entity.BjRoleDto;
import com.bajie.bjlisten.mapper.BjRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class BjRoleService {
    private static final Logger log = LoggerFactory.getLogger("adminLogger");
    @Autowired
    private BjRoleMapper bjRoleMapper;

    @Transactional
    public void saveRole(BjRoleDto roleDto) {
        BjRole role = roleDto;

        if (role.getId() != null) {// 修改
            BjRole r = bjRoleMapper.getRoleByName(role.getRole_name());
            if (r != null && r.getId() != role.getId()) {
                throw new IllegalArgumentException(role.getRole_name() + "已存在");
            }

            bjRoleMapper.updateByRole(role);
        } else {// 新增
            BjRole r = bjRoleMapper.getRoleByName(role.getRole_name());
            if (r != null) {
                throw new IllegalArgumentException(role.getRole_name() + "已存在");
            }

            bjRoleMapper.saveRole(role);

            log.debug("新增角色{}", role.getRole_name());
        }

        saveRolePermission(role.getId(), roleDto.getPermissionIds());
    }

    /**
     * 保存角色权限
     *
     * @param roleId
     * @param menuIds
     */
    private void saveRolePermission(String roleId, List<String> menuIds) {
        //根据角色ID删除角色表
        bjRoleMapper.deleteRolePermission(roleId);
        //menuIds.remove(0L);
        //判断菜单ID集合是否为空
        if (!CollectionUtils.isEmpty(menuIds)) {
            //根据角色ID和菜单ID集合保存角色权限
            bjRoleMapper.saveRolePermission(roleId, menuIds);
        }
    }

    /**
     * 根据角色ID 删除角色表/角色菜单关联表/角色用户表
     *
     * @param roleId
     */

    @Transactional
    public void deleteRole(String roleId) {
        bjRoleMapper.deleteRolePermission(roleId);
        bjRoleMapper.deleteRoleUser(roleId);
        bjRoleMapper.deleteById(roleId);

        log.debug("删除角色id:{}", roleId);
    }
}
